package com.writing.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.writing.entity.Character;
import com.writing.entity.Novel;
import com.writing.mapper.CharacterMapper;
import com.writing.service.CharacterService;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * 人物服务实现类
 */
@Service
@RequiredArgsConstructor
public class CharacterServiceImpl extends ServiceImpl<CharacterMapper, Character> implements CharacterService {

    @Override
    public List<Character> getCharactersByNovelId(Long novelId) {
        return this.list(new LambdaQueryWrapper<Character>()
                .eq(Character::getNovelId, novelId)
                .orderByAsc(Character::getId));
    }

    @Override
    public Character getCharacterById(Long characterId, Long novelId) {
        return this.getOne(new LambdaQueryWrapper<Character>()
                .eq(Character::getId, characterId)
                .eq(Character::getNovelId, novelId));
    }

    @Override
    public Character createCharacter(Character character) {
        // 设置默认值
        if (character.getRole() == null) {
            character.setRole("supporting");
        }
        if (character.getGender() == null) {
            character.setGender("male");
        }
        if (character.getGenerated() == null) {
            character.setGenerated(0); // 0表示非AI生成，1表示AI生成
        }

        this.save(character);
        return character;
    }

    @Override
    public Character updateCharacter(Character character) {
        // 验证人物是否存在
        Character existingCharacter = this.getOne(new LambdaQueryWrapper<Character>()
                .eq(Character::getId, character.getId())
                .eq(Character::getNovelId, character.getNovelId()));

        if (existingCharacter == null) {
            throw new RuntimeException("人物不存在");
        }

        this.updateById(character);
        return character;
    }

    @Override
    public boolean deleteCharacter(Long characterId, Long novelId) {
        // 验证人物是否存在
        Character character = this.getOne(new LambdaQueryWrapper<Character>()
                .eq(Character::getId, characterId)
                .eq(Character::getNovelId, novelId));

        if (character == null) {
            throw new RuntimeException("人物不存在");
        }

        return this.removeById(characterId);
    }
}
